//
//  EFAFeedbackVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/9/18.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAFeedbackVC.h"
#import "EFANoticePubCCell.h"
#import "EFAFeedbackCRView.h"
#import "EFANotPubPjtCCell.h"
#import <TZImagePickerController.h>
#import <TZImageManager.h>
#import "XDQiniuManager.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "UIColor+XDHex.h"
#import "EFAModel.h"
#import "EFANotSelModeVC.h"

@interface EFAFeedbackVC ()<UICollectionViewDelegate, UICollectionViewDataSource, TZImagePickerControllerDelegate, EFANoticePubCCellDelegate>
@property (weak,   nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) UIBarButtonItem *cancelBarBtnItem;
@property (nonatomic, strong) UIBarButtonItem *publishBarBtnItem;
@property (nonatomic, strong) EFAFeedbackModel *pubModel;
@end

static NSString *const kReuseCellId = @"EFANoticePubCCell";
static NSString *const kReuseCRViewId = @"EFAFeedbackCRView";
static NSInteger const kMaxPictureCnt = 3;

@implementation EFAFeedbackVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"用户反馈";
    self.navigationItem.leftBarButtonItem = self.cancelBarBtnItem;
    self.navigationItem.rightBarButtonItem = self.publishBarBtnItem;
}

- (void)initSubViews {
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:kReuseCellId];
    UINib *cRViewNib = [UINib nibWithNibName:kReuseCRViewId bundle:nil];
    [self.collectionView registerNib:cRViewNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseCRViewId];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.alwaysBounceVertical = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshWholeView];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return (self.pubModel.image_list.count < kMaxPictureCnt) ? self.pubModel.image_list.count + 1 : kMaxPictureCnt;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    EFANoticePubCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReuseCellId forIndexPath:indexPath];
    EFANotPubItem *item = nil;
    if (indexPath.row < self.pubModel.image_list.count) {
        item = self.pubModel.image_list[indexPath.row];
    }
    [cell configViewWithNotPubItem:item];
    cell.delegate = self;
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && [kind isEqualToString:UICollectionElementKindSectionHeader]) {
        EFAFeedbackCRView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseCRViewId forIndexPath:indexPath];
        header.pubModel = self.pubModel;
        return header;
    }
    return nil;
}

#pragma mark - <UICollectionViewDelegateFlowLayout>
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGSizeMake(CGRectGetWidth(self.view.bounds), 254.0);
    }
    return CGSizeZero;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        CGFloat width = (CGRectGetWidth(self.view.bounds) - 2*15 - 2 * 24) / 3.0;
        return CGSizeMake(width, width);
    }
    
    CGFloat width = CGRectGetWidth(self.view.bounds) - 2*15;
    return CGSizeMake(width, 44.0);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == self.pubModel.image_list.count) {
        // 添加照片
        NSInteger maxCnt = kMaxPictureCnt - self.pubModel.image_list.count;
        TZImagePickerController * pickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:maxCnt delegate:self];
        pickerVC.allowPickingVideo = NO;
        pickerVC.allowTakePicture = NO;
        pickerVC.allowPickingOriginalPhoto = NO;
        [self presentViewController:pickerVC animated:YES completion:nil];
    }
}

#pragma mark - EFANoticePubCCellDelegate
- (void)noticePubCCell:(EFANoticePubCCell *)cell closeBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    [self.pubModel removePublishItemAtIndex:indexPath.row];
    if (indexPath.row == kMaxPictureCnt - 1) {
        [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
    } else {
        if (self.pubModel.image_list.count == kMaxPictureCnt - 1) {
            [self refreshWholeView];
        } else {
            [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
        }
    }
}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    if (isSelectOriginalPhoto) {
        [assets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            //            [[TZImageManager manager] getOriginalPhotoWithAsset:obj newCompletion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
            //                NSLog(@"获取原图%@， --%@, (%zd)", photos, info, isDegraded);
            //                if (!isDegraded) {
            //                    [self.pubModel addPublishItemsWithArray:@[photo]];
            //                    [self refreshWholeView];
            //                }
            //            }];
            
            // 上面一个占用内存太大，导致崩溃。所以只能考虑下面这个获取原图的方法。
            [[TZImageManager manager] getOriginalPhotoDataWithAsset:obj completion:^(NSData *data, NSDictionary *info, BOOL isDegraded) {
                NSLog(@"获取原图--%@, (%zd)", info, isDegraded);
                if (!isDegraded) {
                    if (idx < photos.count) {
                        [self.pubModel addPublishItemsWithImgArray:@[photos[idx]] originalDataArray:@[data]];
                        [self refreshWholeView];
                    }
                }
            }];
        }];
    } else {
        [self.pubModel addPublishItemsWithImgArray:photos originalDataArray:nil];
        [self refreshWholeView];
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    NSLog(@"选择照片缩略图 = %@", photos);
    NSLog(@"选择照片原始的assets = %@", assets);
    NSLog(@"选取照片之后的infos = %@", infos);
}

#pragma mark - event response
- (void)cancelBarBtnTapped:(UIBarButtonItem *)item {
    //    if (self.pubModel.isEmpty) {
    //        [self dismissViewControllerAnimated:YES completion:nil];
    //    } else {
    //        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"离开发布页后，编辑内容将被清空" message:nil preferredStyle:UIAlertControllerStyleAlert];
    //        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    //        [alertVC addAction:[UIAlertAction actionWithTitle:@"离开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //            [[XDQiniuManager sharedInstance] cancelUpload]; //!< 如果有上传的，直接结束上传
    //            [self dismissViewControllerAnimated:YES completion:nil];
    //        }]];
    //        [self presentViewController:alertVC animated:YES completion:nil];
    //    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)publishBarBtnTapped:(UIBarButtonItem *)item {
    // 检查用户输入信息
    if (!self.pubModel.efairyfeedback_content.length) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请输入反馈内容"];
        return;
    }
    
    // 图片上传成功、发布未成功的情况下，直接去发布即可
    if (self.pubModel.isImgUpload) {
        [self requestPublishNotice];
        return;
    }
    
    // 上传图片
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.progress = 0;
    hud.label.text = @"上传图片...";
    
    [[XDQiniuManager sharedInstance] uploadImages:self.pubModel.imgArray progress:^(NSString *key, float percent) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = percent;
        });
    } success:^(NSArray<NSString *> *urlArray) {
        [hud hideAnimated:NO];
        [self.pubModel updateImgUrlWithArray:urlArray];
        // 发表到服务器
        [self requestPublishNotice];
        NSLog(@"开始发表到服务器");
    } failure:^(NSString *error) {
        NSLog(@"上传图片失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:error];
    }];
}
#pragma mark - private methods
- (void)refreshWholeView {
    [self.collectionView reloadData];
}

- (void)exitViewController {
    if (self.successHandle) {
        self.successHandle();
        self.successHandle = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - network request
- (void)requestPublishNotice {
    // 发布公告需要登录
    if (![EFAModel sharedInstance].isLogin) {
        return;
    }
    
    // 发布帖子
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *pubDic = [self.pubModel yy_modelToJSONObject];
    [pubDic setObject:self.pubModel.urlArray forKey:@"efairyfeedback_imgurl_list"];
    [pubDic removeObjectForKey:@"image_list"];
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyfeedback_info" : pubDic};
    NSLog(@"发布反馈的请求参数：%@", pars);
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiFeedback] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"发布反馈返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"反馈成功"];
        temp.completionBlock = ^{
            [self exitViewController];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"发布反馈失败：%@", error);
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)cancelBarBtnItem {
    if (!_cancelBarBtnItem) {
        _cancelBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_cancelBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_cancelBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _cancelBarBtnItem;
}

- (UIBarButtonItem *)publishBarBtnItem {
    if (!_publishBarBtnItem) {
        _publishBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(publishBarBtnTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_publishBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_publishBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _publishBarBtnItem;
}

- (EFAFeedbackModel *)pubModel {
    if (!_pubModel) {
        _pubModel = [[EFAFeedbackModel alloc] init];
        _pubModel.imgMaxCnt = kMaxPictureCnt;
    }
    return _pubModel;
}
@end
